<template>
  <view :class="classNameList" :visible.sync="posterVisible" background="none" @cancel="closePosterVisible">
    <view class="pc-container">
      <x-image :src="imgurl" @longpress="saveImage"></x-image>
      <canvas canvas-id="myCanvas" id="myCanvas" style="width: 280px;height: 780rpx;margin: 0 auto;border-radius: 5px;overflow: hidden;" v-show="canvasShow"></canvas>
    </view>
  </view>
</template>

<script>
import XImage from '@/components/x-image';

export default {
  name: 'PDrawerPoster',
  components: {
    XImage
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    detail: {
      type: Object,
      detail: () => {}
    }
  },
  data() {
    return {
      posterVisible: this.visible,
      canvasWidth: 375,
      canvasHeight: 1100,
      canvasRatio: 0,
      posterLoad: false,
      wx_mini_qrcode_goods: 'https://alicdn.itaored.com/test/feima-uploaded/images/86/dd/86dd82ef11c7684128815653002c6e06.jpg',
      share_img_width: 0,
      share_img_height: 0,
      goods: {
        title: '阿斯利康等会拉康师傅里肯定能拉丝带回来',
        share_img: 'https://alicdn.itaored.com/test/feima-uploaded/images/86/dd/86dd82ef11c7684128815653002c6e06.jpg',
        goods_price: '19.00',
        market_price: '29.00'
      }
    };
  },
  computed: {
    classNameList() {
      const arr = ['p-poster', `is-${this.direction}`];
      if (this.visible) {
        arr.push('is-show');
      }
      return arr.join(' ');
    }
  },
  created() {
    const _this = this;
    uni.getImageInfo({
      src: 'https://alicdn.itaored.com/test/feima-uploaded/images/86/dd/86dd82ef11c7684128815653002c6e06.jpg',
      success: function(image) {
        // console.log(image);
        _this.goodsImage = image.path;
      }
    });
    setTimeout(function() {
      _this.canvasImage();
    }, 2000);
  },
  watch: {},
  methods: {
    //  生成分享海报
    createNewImg: function() {
      uni.showLoading({
        title: '海报生成中！',
        mask: true
      });
      let canvas = '';
      const query = uni.createSelectorQuery();
      query.select('#mycanvas')
        .fields({ node: true, size: true })
        .exec((res) => {
          console.log(res);
          canvas = res[0].node;
          const ctx = canvas.getContext('2d');
          const dpr = uni.getWindowInfo().pixelRatio;
          canvas.width = res[0].width * dpr;
          canvas.height = res[0].height * dpr;
          ctx.scale(dpr, dpr);
          this.canvasWidth = res[0].width;
          this.canvasHeight = res[0].height;
          this.canvasRatio = res[0].width / 750;
          // 绘制画布矩形背景
          this.canvasBg(ctx);
          this.drawShopImg(canvas, ctx);
        });
    },
    getImageInfo_local: function() { // 获取网络图片到本地地址
      const that = this;
      this.posterVisible = true;
      uni.getImageInfo({
        src: that.goods.share_img, // 服务器返回的图片地址
        success: function(res) {
          // res.path是网络图片的本地地址
          console.log(res);
          that.share_img_width = res.width;
          that.share_img_height = res.height;
          that.createNewImg();
        },
        fail: function(res) {
          // 失败回调
          console.log(res);
        }
      });
    },
    // 绘制图片缩略图
    drawShopImg(canvas, ctx) {
      const that = this;
      const img = canvas.createImage();
      img.src = this.goods.share_img;
      img.onload = () => {
        // ctx.drawImage(img, 0, 40, this.canvasWidth, this.canvasWidth * (this.share_img_height / this.share_img_width));
        ctx.drawImage(img, 0, 0, this.canvasWidth, this.canvasWidth);
        ctx.restore();
        that.drawErCode(canvas, ctx);
      };
    },
    // 绘制二维码图
    drawErCode(canvas, ctx) {
      const that = this;
      const wx_mini_qrcode_goods = that.wx_mini_qrcode_goods;
      if (wx_mini_qrcode_goods) {
        const img = canvas.createImage();
        img.src = wx_mini_qrcode_goods;
        img.onload = () => {
          // console.log(img.complete)
          ctx.drawImage(img, that.canvasWidth - 216 * this.canvasRatio, that.canvasWidth + 42 * this.canvasRatio, 160 * this.canvasRatio, 160 * this.canvasRatio);
          ctx.restore();
          // 绘制价格
          this.canvasPrice(ctx);
          // 绘制标题
          this.canvasTitle(ctx);
          // //绘制右下角扫码提示语
          ctx.font = '14px PingFang SC';
          ctx.fillStyle = '#999999';
          ctx.textAlign = 'left';
          ctx.fillText('扫描或长按二维码', that.canvasWidth - 248 * this.canvasRatio, that.canvasWidth + 250 * this.canvasRatio, 224 * this.canvasRatio, 25);
          // canvas转图片
          uni.canvasToTempFilePath({
            canvas: canvas,
            success: function(res) {
              uni.hideLoading();
              console.log(res);
              // const tempFilePath = res.tempFilePath;
              that.imagePath = res.tempFilePath;
              uni.hideToast();
              that.posterLoad = true;
            },
            fail: function(res) {
              uni.hideLoading();
              uni.showLoading({
                title: '海报生成失败！',
                mask: true
              });
              console.log(res);
            }
          });
        };
      }
    },
    canvasBg(ctx) {
      ctx.fillStyle = '#ffffff';
      ctx.strokeStyle = 'transparent';
      const x = 0;
      const r = 10;
      const y = 0;
      const h = this.canvasHeight;
      const w = this.canvasWidth;
      ctx.arc(x + r, y + r, r, Math.PI, Math.PI * 1.5);
      // border-top
      ctx.moveTo(x + r, y);
      ctx.lineTo(x + w - r, y);
      // 右上角
      ctx.arc(x + w - r, y + r, r, Math.PI * 1.5, Math.PI * 2);
      // border-right
      ctx.lineTo(x + w, y + h - r);
      // 右下角
      ctx.arc(x + w - r, y + h - r, r, 0, Math.PI * 0.5);
      // border-bottom
      ctx.lineTo(x + r, y + h);
      // 左下角
      ctx.arc(x + r, y + h - r, r, Math.PI * 0.5, Math.PI);
      // border-left
      ctx.lineTo(x, y + r);
      ctx.lineTo(x + r, y);
      // 这里是使用 fill 还是 stroke都可以，二选一即可，但是需要与上面对应
      ctx.fill();
      ctx.closePath();
      // 剪切
      ctx.clip();
    },
    //  绘制商品标题
    canvasTitle(ctx) {
      const that = this;
      const title = that.goods.title;
      ctx.font = '18px PingFang SC';
      ctx.fillStyle = '#323233';
      ctx.textAlign = 'left';
      const chr = title.split('');// 这个方法是将一个字符串分割成字符串数组
      let temp = '';
      let row = [];
      for (let a = 0; a < chr.length; a++) {
        if (ctx.measureText(temp).width < (this.canvasWidth * 440 / 750)) {
          temp += chr[a];
        } else {
          a--; // 这里添加了a-- 是为了防止字符丢失，效果图中有对比
          row.push(temp);
          temp = '';
        }
      }
      row.push(temp);
      // 如果数组长度大于2 则截取前两个
      if (row.length > 2) {
        const rowCut = row.slice(0, 2);
        const rowPart = rowCut[1];
        let test = '';
        const empty = [];
        for (let a = 0; a < rowPart.length; a++) {
          if (ctx.measureText(test).width < this.canvasWidth) {
            test += rowPart[a];
          } else {
            break;
          }
        }
        empty.push(test);
        const group = empty[0].slice(0, empty[0].length - 3) + '...';// 这里只显示两行，超出的用...表示
        rowCut.splice(1, 1, group);
        row = rowCut;
      }
      for (let b = 0; b < row.length; b++) {
        ctx.fillText(row[b], 16, that.canvasWidth + 36 + b * 26);
      }
    },
    //  绘制商品价格
    canvasPrice(ctx) {
      const that = this;
      const tips = '¥';
      const price = that.goods.goods_price;
      const market_price = '¥' + that.goods.market_price;
      ctx.font = 'bold 12px PingFang SC';
      ctx.fillStyle = '#EB441F';
      ctx.textAlign = 'left';
      const tipsWidth = ctx.measureText(tips).width;
      ctx.fillText('¥', 16, that.canvasWidth + 252 * this.canvasRatio);
      ctx.stroke();
      ctx.font = 'bold 26px PingFang SC';
      ctx.fillStyle = '#EB441F';
      ctx.textAlign = 'left';
      const priceWidth = ctx.measureText(price).width;
      ctx.fillText(price, 16 + tipsWidth, that.canvasWidth + 252 * this.canvasRatio);
      ctx.stroke();
      // 绘制价格划线见面
      ctx.font = '15px PingFang SC';
      ctx.fillStyle = '#999999';
      ctx.textAlign = 'left';
      const textWidth = ctx.measureText(market_price).width;
      ctx.fillText(market_price, priceWidth + tipsWidth + 22, that.canvasWidth + 252 * this.canvasRatio);
      ctx.stroke();

      // console.log(textWidth)
      ctx.beginPath();
      ctx.rect(priceWidth + tipsWidth + 22, that.canvasWidth + 244 * this.canvasRatio, textWidth, 1);
      ctx.fillStyle = '#999999';
      ctx.fill();
    },
    //  长按保存海报
    longpressSaveImage() {
      uni.showActionSheet({
        itemList: ['保存图片'],
        success: (res) => {
          if (res.tapIndex === 0) {
            uni.saveImageToPhotosAlbum({
              filePath: this.imagePath, //    图片文件路径，可以是临时文件路径也可以是永久文件路径，不支持网络图片路径
              success: () => {
                uni.showToast({
                  title: '保存成功',
                  duration: 2000
                });
                this.posterVisible = false;
              },
              fail: () => {
                uni.showToast({
                  title: '保存失败',
                  duration: 2000
                });
              }
            });
          }
        },
        fail: function(res) {
          console.log(res.errMsg);
        }
      });
    },
    //  点击保存海报
    saveImage() {
      uni.saveImageToPhotosAlbum({
        filePath: this.imagePath, //    图片文件路径，可以是临时文件路径也可以是永久文件路径，不支持网络图片路径
        success: () => {
          uni.showToast({
            title: '保存成功',
            duration: 2000
          });
          this.posterVisible = false;
        },
        fail: () => {
          uni.showToast({
            title: '保存失败',
            duration: 2000
          });
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.p-poster{
  position: fixed; width: 100%; height: 100%; z-index: 1000; left: 0; top: 0; display: none; overflow: hidden;background-color: rgba(0,0,0,.5);
  &.is-show{
    display: block;
  }
}
</style>
